<script lang="ts" setup>
import { reactive, ref } from 'vue'
//引入登录api
import { doPostSmsCode, signByUser } from '@/apis'
import { useShopInfoStore } from '@/store/modules/shopInfo'
import { doGetShopInfo } from '@/apis/afs'
import { GrantType } from '@/apis/sign/type'
import { onLoad, onShow } from '@dcloudio/uni-app'
import SliderCaptcha from '@/components/slide-captcha/SliderCaptcha.vue'

//表单正则表达式
const mobileRegex = /^1[3-9][0-9]{9}$/
const codeRegex = /^\d{4}$/
// 获取验证码倒计时 dom ref
const codeCountdownRef = ref()

onLoad(() => {
    uni.$emit('updateTitle')
})
onShow(() => {
    console.log('是否有token', useShopInfoStore().shopInfo?.token)

    if (useShopInfoStore().getterShopInfo?.token) {
        // 如果有token，跳转到首页
        uni.reLaunch({
            url: '/pages/platform/index',
        })
    }
})

const form = reactive<any>({
    //账号
    mobile: {
        value: '',
    },
    //密码
    code: {
        value: '',
        password: false,
        iconclick: false,
        icon: '',
    },
    //选择的店铺
    shop: null,
    //获取店铺列表的数据
    shops: [],
    //控制弹窗
    showshoplist: false,
})
const codeText = ref('获取验证码')
// 判断登录方式状态
const codetype = ref(true)
//验证码禁用
const codeDisabled = ref(false)
// 控制验证码组件的显示
const showSliderCaptcha = ref(false)
/**
 * 改变密码框的状态和图标的函数
 */
const handlerChangeIcon = (): void => {
    // 改变密码框的状态
    form.code.password = !form.code.password
    // 改变密码框的图标
    form.code.password ? (form.code.icon = 'eye') : (form.code.icon = 'eye-fill')
}
/**
 * 发送登录请求的函数
 */
const handleSubmit = (): void => {
    const mobile = form.mobile.value
    if (!mobile || !mobileRegex.test(mobile)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
            duration: 1000,
        })
        return
    }
    const code = form.code.value
    if (!code || !codeRegex.test(code)) {
        uni.showToast({
            title: '请输入正确的验证码',
            icon: 'none',
            duration: 1000,
        })
        return
    }
    const grantType = codetype.value ? GrantType.SMS_CODE : GrantType.PASSWORD
    const data = codetype.value
        ? {
              mobile: form.mobile.value,
              code: form.code.value,
          }
        : {
              username: form.mobile.value,
              password: form.code.value,
          }
    signByUser(grantType, data).then(async ({ code, data, msg }: any) => {
        if (code !== 200) {
            codeCountdownRef.value?.reset()
            codeDisabled.value = false
            uni.showToast({
                title: msg,
                icon: 'none',
                duration: 2000,
            })
            return
        }
        const { value, refreshToken, open } = data
        //将token存入store
        useShopInfoStore().SET_SHOP_TOKEN({ access_token: value, refresh_token: refreshToken.value })
        useShopInfoStore().SET_SHOP_Id(open.shopId)
        const shopResult = await doGetShopInfo(open.shopId)
        const shopData = shopResult?.data
        if (shopData) {
            useShopInfoStore().SET_SHOP_INFO(shopData)
        }
        console.log('uni.reLaunch')
        uni.reLaunch({
            url: '/pages/platform/index',
        })
    })
}

const formRules = ref({
    mobile: [
        {
            required: true,
            message: '请输入手机号',
            trigger: ['blur', 'change'],
        },
    ],
    code: [
        {
            required: true,
            message: '请输入验证码',
            trigger: ['blur', 'change'],
        },
    ],
})
/**
 *  点击切换登录方式函数
 */
const handleChangeCode = (): void => {
    //清空商铺列表
    form.shops = []
    //清空选择的店铺
    form.shop = null
    // 切换登录方式并且 通过codetype切换图标显示的内容
    codetype.value = !codetype.value
    form.code.icon = codetype.value ? '' : 'eye'
    // 切换登录方式后清空输入框的内容
    form.code.value = ''
    form.mobile.value = ''
}

/**
 * 获取验证码的函数
 */
const getCode = (): void => {
    const mobile = form.mobile.value
    if (!mobile || !mobileRegex.test(mobile)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
            duration: 1500,
        })
        return
    }
    if (codeCountdownRef.value?.canGetCode) {
        showSliderCaptcha.value = true
    }
}

const sendSmsCodeSuccess = ({ data }: { data: string }) => {
    codeCountdownRef.value?.start()
    codeDisabled.value = true
    showSliderCaptcha.value = false
    form.code.value = data
}
</script>

<template>
    <view class="login">
        <view class="login__top">
            <view class="login__top--firsttital">登录</view>
            <view class="login__top--secondtital">商家移动端</view>
        </view>
        <view class="login__bottom">
            <fieldset class="login__bottom--fields">
                <legend class="login__title">{{ codetype ? '手机号' : '账号' }}</legend>
                <u-field v-model="form.mobile.value" :border-bottom="false" label-width="0" maxlength="11" placeholder="请填写手机号" required trim />
            </fieldset>
            <fieldset class="login__bottom--fields">
                <legend class="login__title">{{ codetype ? '验证码' : '密码' }}</legend>
                <u-field
                    v-model="form.code.value"
                    :border-bottom="false"
                    :maxlength="codetype ? '4' : '20'"
                    :password="form.code.password"
                    :placeholder="codetype ? '请填写验证码' : '请填写密码'"
                    :right-icon="form.code.icon"
                    label-width="0"
                    required
                    trim
                    @right-icon-click="handlerChangeIcon"
                >
                    <template v-if="codetype" #right>
                        <u-button slot="right" :disabled="codeDisabled" size="mini" @click="getCode">{{ codeText }}</u-button>
                    </template>
                </u-field>
            </fieldset>
            <button class="login__bottom--submit" @click="handleSubmit">登录</button>
            <!--            <button class="login__bottom&#45;&#45;other" @click="handleChangeCode">其他方式登录</button>-->
        </view>
    </view>
    <u-verification-code
        ref="codeCountdownRef"
        seconds="60"
        @change="(tips:string) => (codeText = tips)"
        @end="codeDisabled = false"
    ></u-verification-code>
    <slider-captcha
        v-model="showSliderCaptcha"
        :do-submit="doPostSmsCode"
        :get-form="() => form.mobile.value"
        :scale="2"
        @success="sendSmsCodeSuccess"
    />
</template>

<style lang="scss" scoped>
@include b(login) {
    height: 100vh;
    display: flex;
    flex-direction: column;
    text-align: center;
    background-color: rgba(255, 255, 255, 1);
    @include e(top) {
        height: 590rpx;
        width: 100vw;
        background: url('https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul111/2024/11/467285c2072ade2c8504fc20c.png') no-repeat
            fixed;
        background-size: 750rpx 590rpx;
        position: relative;
        text-align: left;
        font-family: AlibabaSans-regular, serif;
        color: rgba(255, 255, 255, 1);
        @include m(firsttital) {
            position: absolute;
            left: 54rpx;
            top: 160rpx;
            height: 36rpx;
            font-size: 40rpx;
        }

        @include m(secondtital) {
            position: absolute;
            left: 54rpx;
            top: 248rpx;
            height: 46rpx;
            font-size: 70rpx;
        }
    }
    @include e(bottom) {
        flex: 1;
        @include m(fields) {
            border: 2rpx solid #2a29e8;
            border-radius: 20rpx;
            margin: 63rpx 54rpx;
            padding: 0;
            height: 100rpx;
        }
        @include m(submit) {
            width: 400rpx;
            height: 76rpx;
            line-height: 76rpx;
            border-radius: 92rpx;
            background: linear-gradient(-84.98deg, rgba(42, 41, 232, 1) 3.82%, rgba(71, 85, 233, 1) 95.62%);
            color: rgba(250, 250, 250, 1);
            font-size: 28rpx;

            font-family: Arial, serif;
            margin-bottom: 40rpx;
        }
        @include m(other) {
            width: 250rpx;
            height: 60rpx;
            line-height: 60rpx;
            border-radius: 70rpx;
            background-color: rgba(244, 244, 244, 1);
            color: #101010;
            font-size: 24rpx;
            font-family: Arial, serif;
        }
    }
    @include e(title) {
        text-align: left;
        font-size: 24rpx;
        margin-left: 44rpx;
        color: #4c55bc;
        font-weight: bolder;
    }
}

@include b(shop) {
    @include e(item) {
        display: flex;
        align-items: center;
        border: 2px solid #6d6d6e;
        border-radius: 20rpx;
        margin: 20rpx 20rpx 0 20rpx;
        overflow: hidden;
        box-shadow: 0px 4px 8px 0px #6d6d6e;
    }
}

:deep(.u-label) {
    flex: 0 0 0;
}

:deep(.u-field) {
    padding: 0 40rpx;
}

:deep(.uni-input-input) {
    font-size: 24rpx;
}

:deep(.selectorshopbtn) {
    border-radius: 92rpx;
    background: linear-gradient(-84.98deg, rgba(42, 41, 232, 1) 3.82%, rgba(71, 85, 233, 1) 95.62%);
    color: rgba(250, 250, 250, 1);
    font-size: 24rpx;
}
</style>
